﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel.Composition;
using System.Web;
using System.Diagnostics.CodeAnalysis;

namespace Steve.UI.Extensions
{
    [Export(typeof(RewriterBase))]
    public class DefaultRewriter : RewriterBase
    {
        [Import]
        public ILoggingService Log { get; set; }

        public override RewriteResult Rewrite(Uri requestUrl, UrlObject match)
        {
            if (requestUrl == null) throw new ArgumentNullException("requestUrl");

            if (match != null)
            {
                RewriteResult result = null;
                var rewrite = match as RewriteUrl;
                var site = SiteExplorer.GetSite(match.SiteName);

                if (rewrite != null)
                {

                    result = new RewriteResult() { From = rewrite };

                    //if a rewrite found...
                    result.To = SiteExplorer.GetSiteUrl(rewrite.SiteUrlId);
                    result.ToUrl = result.To.ToUri(SiteExplorer);

                    //TODO: handle internal rewrites instead of just 301's?
                }
                else
                {
                    var live = match as SiteUrl;

                    if (live != null)
                    {
                        //TODO: maybe some different handling of SSL, since we have issues with 
                        //stuff like proxy, etc that may make it show non secure even when 
                        //it is secure...
                        var testUrl = live.IgnoreQueryString ? requestUrl.AbsolutePath : requestUrl.PathAndQuery;                        

                        //check: secure / unsecure, casing, alt authorities, etc...
                        if (live.IsSecure != (requestUrl.Scheme == "https") ||
                            !testUrl.EndsWith(live.Url, StringComparison.Ordinal) ||
                            !site.Authority.Equals(requestUrl.Authority, StringComparison.OrdinalIgnoreCase))
                        {
                            //url doesn't match, so rewrite to passed url
                            result = new RewriteResult() { To = live, ToUrl = live.ToUri(SiteExplorer) };
                        }

                    }
                }

                return result;
            }
#if TRACE
            else
            {
                Log.Warn(TraceCategory.SiteModule, "Url not matched in Steve directory");
            }
#endif

            return null;
        }
    }
}
